<template>
    <div class="container">
        <div style="margin: 20px;">
            <span class="_before">账单利润趋势</span>
            <ControlPanel :dataType="3" :timePeriod="timeInterval" :refType = '5' @updateValue='updateLineChart'></ControlPanel>
            <div style="width: 90%;height: 300px;margin-top: 30px;">
                <VueUiLinegraph :xAxisLineValue="xAxisLineValue" :yAxisLineValueUSD="yAxisLineValueUSD" :yAxisLineValueCNY="yAxisLineValueCNY"></VueUiLinegraph>
            </div>
        </div>
        <div style="margin: 50px;">
            <el-radio-group v-model="profitAnalysis" style="margin-bottom: 30px">
                <el-radio-button value="profitTrend">客户利润趋势</el-radio-button>
                <el-radio-button value="profitShare">客户利润占比</el-radio-button>
            </el-radio-group>
           
            <template v-if="profitAnalysis == 'profitTrend'">
                <ControlPanel :dataType="3" :timePeriod = "timeInterval" :refType = '5' @updateValue='updateBarChart'></ControlPanel>
                <div style="width: 90%;height: 400px;margin-top: 20px;">
                    <VueUiPieXy :xAxisValue="xAxisValue" :axisValueUsd="axisValueUsd" :axisValueCny="axisValueCny"></VueUiPieXy>
                </div>
            </template>
            <template v-if="profitAnalysis == 'profitShare'">
                <ControlPanel :dataType="3" :timePeriod = "timeInterval" :refType = '5' :currency="'USD'" @updateValue='updatePieChart' :isShow="true"></ControlPanel>
                <div style="width: 50%;margin-top: 20px;">
                    <VueUiDonut :axisPieValueName="axisPieValueName" :axisPieValue="axisPieValue"></VueUiDonut>
                </div>
            </template>
        </div>
    </div> 
</template>
<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import { billProfitCountDate, billProfitCountCompany, billProfitProportionCountCompany} from '@/api/financial/bills'
import { ElMessage } from 'element-plus'
import VueUiLinegraph from '@/components/vueDataUI/uiLinegraph'
import VueUiPieXy from '@/components/vueDataUI/uiPieXy'
import VueUiDonut from '@/components/vueDataUI/uiDonut'
import ControlPanel from '@/views/financialManage/analysis/controlPanel'
import { differenceInDays, parse } from 'date-fns';

const profitAnalysis = ref("profitTrend")

const dataType = ref('3') // //数据类型: 3-日 5-月份 10-季度 15-年份
const timeInterval = ref(["20250601","20250607"]) //查询时间区间
const refType = ref('5') // //账单业务类型 5-租箱  10-回调 20-售箱 25-购箱 30-代管箱
const currency = ref('USD') // 币种类型
onMounted(() => {
    timeInterval.value.length = 0
    timeInterval.value.push(getCurrentDate('current'))
    timeInterval.value.push(getCurrentDate(7))
    let resParams = {
        dataType:dataType.value,
        refType:refType.value,
        currency:currency.value,
        timePeriod:timeInterval.value
    }
    updateLineChart(resParams)
    updateBarChart(resParams)
    updatePieChart(resParams)
})

//更新折线图
const xAxisLineValue = ref(['2025-06-20','2025-06-21'])
const yAxisLineValueUSD = ref([])
const yAxisLineValueCNY = ref([])
const updateLineChart = async (lineVal) => { 
    console.log("lineVal",lineVal)
    let dataType = lineVal.dataType
    let timePeriod = lineVal.timePeriod
    let refType = lineVal.refType
    if(dataType == "3"){ //日期类型 日
        if(timePeriod[0] && timePeriod[1]){
            if(Math.abs(getDateDiff(timePeriod[0],timePeriod[1])) >= 31 ){
                return ElMessage.warning('时间间隔不能超过31天')
            }
        }  
    }
    const resParams = {
        dataType:dataType,
        refType:refType,
        beginDataTime: timePeriod[0],
        endDataTime: timePeriod[1]
    }
    billProfitCountDate(resParams).then(res =>{
        console.log("res",res)
        if(res.code == "00000"){
            xAxisLineValue.value.length = 0
            yAxisLineValueUSD.value.length = 0
            yAxisLineValueCNY.value.length = 0
           res.data.forEach(item => { 
            let time = item.dataTime.toString().replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3")
                xAxisLineValue.value.push(time)
                yAxisLineValueUSD.value.push(item.usdAmount)
                yAxisLineValueCNY.value.push(item.cnyAmount)
           }) 
        }

    })
}

// 更新柱状图
const xAxisValue = ref(['河南亚航','河南陆海'])
const axisValueUsd = ref([1,2])
const axisValueCny = ref([3,4])
const updateBarChart = async (barVal) => { 
    console.log("barVal",barVal)
    let dataType = barVal.dataType
    let timePeriod = barVal.timePeriod
    let refType = barVal.refType
    if(timePeriod && timePeriod.length == 2){
        if(Math.abs(getDateDiff(timePeriod[0],timePeriod[1])) >= 31 ){
            return ElMessage.warning('时间间隔不能超过31天')
        }  
    }else{ 
        return ElMessage.warning('请选择时间区间')
    }

    let resParams = {
        dataType:dataType,
        refType:refType,
        beginDataTime:timePeriod[0],
        endDataTime:timePeriod[1] 
    }
    billProfitCountCompany(resParams).then(res => { 
        console.log("bar",res)
        xAxisValue.value.length = 0
        axisValueUsd.value.length = 0
        axisValueCny.value.length = 0
        if(res.code == '00000'){
            res.data.forEach((item,index)=>{ 
                if(index < 10){
                    xAxisValue.value.push(item.settlementCompanyName)
                    axisValueUsd.value.push(item.usdAmount)
                    axisValueCny.value.push(item.cnyAmount)
                }
            })
        }

    })  

}

// 更新饼状图 billProfitProportionCountCompany
const axisPieValueName = ref(['河南亚航','河南陆海'])
const axisPieValue = ref(["10","20"])
const updatePieChart = (pieVal) => { 
    console.log("pieVal",pieVal)
    let dataType = pieVal.dataType
    let timePeriod = pieVal.timePeriod
    let refType = pieVal.refType
    let currency = pieVal.currency

    let resParams = {
        dataType:dataType,
        refType:refType,
        currency:currency,
        beginDataTime: timePeriod[0],
        endDataTime: timePeriod[1]
    }
    billProfitProportionCountCompany(resParams).then(res => { 
      console.log("pie",res) 
      axisPieValueName.value.length = 0
      axisPieValue.value.length = 0
      if(res.code == '00000'){
        res.data.forEach((item,index)=>{ 
            if(index < 10){
                axisPieValueName.value.push(item.settlementCompanyName)
                axisPieValue.value.push(item.amount)
            }
        })
      } 
    })
}

// 获取日期
const getCurrentDate = (type:any)=>{ //current:当前日期  30:30天之后的日期
    let year:number
    let month =''
    let day =''
    const now = new Date();
    let standardTime = new Date()
    if(type == 'current'){
        standardTime = now
    }else{ 
        const futureDate = new Date(now);
        futureDate.setDate(now.getDate() + type);
        standardTime = futureDate
    }
    year = standardTime.getFullYear();
    month = String(standardTime.getMonth() + 1).padStart(2, '0'); // 月份从0开始
    day = String(standardTime.getDate()).padStart(2, '0'); 
    return `${year}${month}${day}`;
    
}


function getDateDiff(dateStr1: string, dateStr2: string): number {
  // 1. 解析字符串为 Date 对象
  const parseCustomDate = (str: string) => {
    return parse(str, 'yyyyMMdd', new Date());
  };

  // 2. 直接计算天数差
  return differenceInDays(
    parseCustomDate(dateStr2),
    parseCustomDate(dateStr1)
  );
}
</script>

<style lang="scss" scoped></style>